//
//  WBUserAcount.swift
//  WeiBoApp
//
//  Created by James on 2017/7/12.
//  Copyright © 2017年 James. All rights reserved.
//

import UIKit


///用户账号信息
class WBUserAcount: NSObject {
    ///令牌
    var access_token:String?
    
    ///过期时间
    ///开发者是5年 每次登陆之后，都是5年
    ///使用者是3天  会从第一次登陆递减
    var expires_in:TimeInterval = 0{
        didSet{
            expires_Date = Date(timeIntervalSinceNow: expires_in)
        }
    }
    
    
    ///授权用户的UID{
    var uid:String?
    
    ///过期日期
    var expires_Date:Date?
    
    ///用户昵称
    var screen_name:String?
    
    ///头像大图
    var avatar_large:String?
    
    ///存放用户信息的地址
    var userAcountPath:String {
        let documentPath =  FileManager.documentsPath() ?? ""
        let filePath = documentPath.appending("/userAcount.json")

        return filePath
    }
    
    func saveAcount(){
        //1.模型转字典
        var dict = self.yy_modelToJSONObject() as? [String:AnyObject]
        
       _ = dict?.removeValue(forKey: "expires_in")  //不需要保存过期的秒数
        
        //2.字典序列化 data
       guard let data = try? JSONSerialization.data(withJSONObject: dict, options: [])else{
            return
        }
        //3.写入磁盘
        (data as NSData).write(toFile: userAcountPath, atomically: true)
        print(userAcountPath)
    }
    
    override init() {
        super.init()
        //1.加载保存在本地的信息
        
        
        guard let data = NSData(contentsOfFile: userAcountPath) ,let dict = try? JSONSerialization.jsonObject(with: data as Data , options: []) as? [String:AnyObject] else{
            
            return
        }
        
        yy_modelSet(with: dict ?? [:])
        
        print("从沙盒获取用户信息\(self)")
        
//        expires_Date = Date(timeIntervalSinceNow: -3600*24) //测试过期日期
        
        //2.判断token是否过期
        if expires_Date?.compare(Date()) != .orderedDescending {
            print("过期了")
            access_token = nil
            uid = nil
            //清空本地账户文件
            FileManager.removeFile(atPath: userAcountPath)
            
        }
        
        print("token 没过期")
        
    }
    
    
    override var description: String{
        return yy_modelDescription()
    }
}
